<template>
  <div class="group-buy">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="拼购详情"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />
    
    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading" />
    
    <!-- 拼购内容 -->
    <template v-else>
      <!-- 商品信息卡片 -->
      <div class="product-card">
        <div class="product-info">
          <img :src="product.image" :alt="product.name" />
          <div class="product-details">
            <h3>{{ product.name }}</h3>
            <div class="price-info">
              <span class="group-buy-price">¥{{ product.groupBuyPrice }}</span>
              <span class="original-price">¥{{ product.originalPrice }}</span>
            </div>
            <div class="store-name">{{ product.storeName }}</div>
          </div>
        </div>
      </div>

      <!-- 拼购进度 -->
      <div class="progress-card">
        <div class="progress-header">
          <h3>拼购进度</h3>
          <div class="progress-status">
            <span class="sold-count">{{ groupBuy.soldShares }}</span>
            <span class="separator">/</span>
            <span class="total-count">{{ groupBuy.totalShares }}</span>
          </div>
        </div>
        
        <van-progress 
          :percentage="progressPercentage" 
          :show-pivot="false"
          color="#ff6b6b"
        />
        
        <div class="progress-info">
          <span>还差 {{ remainingShares }} 人成团</span>
          <span class="time-remaining">剩余时间：{{ timeRemaining }}</span>
        </div>
      </div>

      <!-- 拼购规则 -->
      <div class="rules-card">
        <h3>拼购规则</h3>
        <div class="rules-list">
          <div class="rule-item">
            <van-icon name="clock-o" />
            <span>拼购时间：24小时</span>
          </div>
          <div class="rule-item">
            <van-icon name="friends-o" />
            <span>成团条件：达到{{ groupBuy.totalShares }}人</span>
          </div>
          <div class="rule-item">
            <van-icon name="success" />
            <span>成团后：自动生成储值卡</span>
          </div>
          <div class="rule-item">
            <van-icon name="close" />
            <span>未成团：自动退款</span>
          </div>
        </div>
      </div>

      <!-- 参与记录 -->
      <div class="participants-card">
        <h3>参与记录</h3>
        <div v-if="participants.length > 0" class="participants-list">
          <div v-for="participant in participants" :key="participant.id" class="participant-item">
            <div class="participant-info">
              <img :src="participant.avatar" :alt="participant.nickname" />
              <span class="nickname">{{ participant.nickname }}</span>
            </div>
            <span class="join-time">{{ formatTime(participant.joinTime) }}</span>
          </div>
        </div>
        <div v-else class="empty-participants">
          <van-empty description="暂无参与记录" />
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="bottom-bar">
        <div class="price-display">
          <span class="label">拼购价</span>
          <span class="price">¥{{ (product.groupBuyPrice * selectedShares).toFixed(2) }}</span>
          <span class="unit-price" v-if="selectedShares > 1">(¥{{ product.groupBuyPrice }}/份)</span>
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span style="font-size: 14px; color: #666;">份数</span>
          <van-stepper
            v-model="selectedShares"
            :min="1"
            :max="remainingShares"
            integer
            input-width="48px"
            style="width: 120px;"
            :disabled="!canJoin"
          />
        </div>
        <van-button 
          type="primary" 
          size="large" 
          :disabled="!canJoin"
          @click="joinGroupBuy"
        >
          {{ joinButtonText }}
        </van-button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'

const route = useRoute()
const router = useRouter()

// 加载状态
const loading = ref(true)

// 商品数据
const product = ref({
  id: 0,
  name: '',
  image: '',
  originalPrice: 0,
  groupBuyPrice: 0,
  totalGroupBuyPrice: 0,
  storeName: '',
  storeLogo: ''
})

// 拼购数据
const groupBuy = ref({
  id: 0,
  soldShares: 0,
  totalShares: 0,
  startTime: new Date(),
  duration: 24 * 60 * 60 * 1000
})

// 参与记录
const participants = ref<any[]>([])

// 计算进度百分比
const progressPercentage = computed(() => {
  if (groupBuy.value.totalShares === 0) return 0
  return Math.round((groupBuy.value.soldShares / groupBuy.value.totalShares) * 100)
})

// 计算剩余份额
const remainingShares = computed(() => {
  return groupBuy.value.totalShares - groupBuy.value.soldShares
})

// 计算剩余时间
const timeRemaining = computed(() => {
  const startTime = new Date(groupBuy.value.startTime)
  const endTime = new Date(startTime.getTime() + groupBuy.value.duration)
  const now = new Date()
  const diff = endTime.getTime() - now.getTime()
  
  if (diff <= 0) return '已结束'
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  return `${hours}小时${minutes}分钟`
})

// 是否可以参与拼购
const canJoin = computed(() => {
  // 检查是否还有剩余份额
  if (remainingShares.value <= 0) return false
  
  // 检查拼购是否已结束（这里简化判断，主要看份额）
  return true
})

// 参与按钮文本
const joinButtonText = computed(() => {
  if (remainingShares.value <= 0) return '已满员'
  return '立即参与'
})

const selectedShares = ref(1)

// 获取拼购详情
const fetchGroupBuyDetail = async (groupBuyId: string) => {
  try {
    const response = await fetch(`/api/group-buy/${groupBuyId}`)
    
    if (!response.ok) {
      throw new Error('获取拼购详情失败')
    }
    
    const data = await response.json()
    
    // 更新商品数据
    product.value = {
      id: data.product.id,
      name: data.product.name,
      image: data.product.images[0] || '',
      originalPrice: data.product.originalPrice,
      groupBuyPrice: data.product.groupBuyPrice / data.totalShares, // 单份价格 = 总价 / 总份数
      totalGroupBuyPrice: data.product.groupBuyPrice, // 保存总价
      storeName: data.product.storeName,
      storeLogo: data.product.storeLogo
    }
    
    // 更新拼购数据
    groupBuy.value = {
      id: data.id,
      soldShares: data.soldShares,
      totalShares: data.totalShares,
      startTime: new Date(data.startTime),
      duration: data.duration
    }
    
    // 更新参与记录
    participants.value = data.participants || []
    
  } catch (error) {
    console.error('获取拼购详情错误:', error)
    showToast('获取拼购详情失败')
  } finally {
    loading.value = false
  }
}

// 参与拼购
const joinGroupBuy = async () => {
  try {
    await showConfirmDialog({
      title: '确认参与拼购',
      message: `确定要参与\"${product.value.name}\"的拼购吗？\n拼购价：¥${product.value.groupBuyPrice} x ${selectedShares.value} = ¥${(product.value.groupBuyPrice * selectedShares.value).toFixed(2)}`,
      confirmButtonText: '确认参与',
      cancelButtonText: '取消'
    })
    
    // 调用参与拼购API
    const response = await fetch(`/api/group-buy/${groupBuy.value.id}/join`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        phone: '18368194001', // TODO: 从用户信息获取
        shares: selectedShares.value
      })
    })
    
    if (!response.ok) {
      throw new Error('参与拼购失败')
    }
    
    const result = await response.json()
    
    if (result.success) {
      showToast('参与成功！')
      // 跳转到支付页面
      router.push({
        name: 'Payment',
        params: { orderId: result.orderId },
        query: {
          store_name: product.value.storeName,
          store_logo: product.value.storeLogo,
          product_name: product.value.name,
          product_image: product.value.image,
          shares: selectedShares.value.toString(),
          total_amount: (product.value.groupBuyPrice * selectedShares.value).toFixed(2)
        }
      })
    } else {
      showToast(result.message || '参与失败')
    }
    
  } catch (error) {
    if (error === 'cancel') return
    console.error('参与拼购错误:', error)
    showToast('参与拼购失败')
  }
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  // 根据路由参数获取拼购详情
  const groupBuyId = route.params.id as string
  if (groupBuyId) {
    fetchGroupBuyDetail(groupBuyId)
  } else {
    showToast('拼购ID无效')
    loading.value = false
  }
})
</script>

<style scoped>
.group-buy {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.product-card {
  background: white;
  margin: 10px;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-info {
  display: flex;
  gap: 15px;
}

.product-info img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  line-height: 1.4;
}

.price-info {
  margin-bottom: 8px;
}

.group-buy-price {
  color: #ff6b6b;
  font-size: 18px;
  font-weight: bold;
  margin-right: 8px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.store-name {
  color: #666;
  font-size: 12px;
}

.progress-card {
  background: white;
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.progress-header h3 {
  margin: 0;
  font-size: 16px;
}

.progress-status {
  display: flex;
  align-items: center;
  gap: 4px;
}

.sold-count {
  color: #ff6b6b;
  font-size: 18px;
  font-weight: bold;
}

.separator {
  color: #999;
  font-size: 14px;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}

.time-remaining {
  color: #ff6b6b;
  font-weight: bold;
}

.rules-card {
  background: white;
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.rules-card h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rule-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.rule-item .van-icon {
  color: #ff6b6b;
}

.participants-card {
  background: white;
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.participants-card h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.participants-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.participant-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.participant-item:last-child {
  border-bottom: none;
}

.participant-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.participant-info img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 14px;
  color: #333;
}

.join-time {
  font-size: 12px;
  color: #999;
}

.empty-participants {
  padding: 20px 0;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 15px;
  z-index: 100;
}

.price-display {
  flex: 1;
}

.price-display .label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.price-display .price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b6b;
}

.price-display .unit-price {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}
</style> 